package integral

import (
	"context"
	"fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/backend/common/i18n"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type ExecIntegralTaskLogLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewExecIntegralTaskLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExecIntegralTaskLogLogic {
	return &ExecIntegralTaskLogLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// #25.02.18#  执行积分任务
func (l *ExecIntegralTaskLogLogic) ExecIntegralTaskLog(in *user.IntegralTaskInfo) (*user.BaseResp, error) {
	logx.Infof("ExecIntegralTaskLog : %+v ", in)
	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, resultx.StatusError(resultx.DB_ERROR, "")
	}
	now := time.Now()
	// integral ==》 []user
	// 判断今天该用户完成该任务次数是否已上线
	filterMap := make(map[string]map[string][]any)
	filterMap[model.UserTaskLogColumns.UserID] = map[string][]any{
		"equalTo": {*in.UserId},
	}
	filterMap[model.UserTaskLogColumns.TaskID] = map[string][]any{
		"equalTo": {*in.TaskId},
	}
	filterMap[model.UserTaskLogColumns.TaskName] = map[string][]any{
		"equalTo": {*in.TaskName},
	}
	// 获取当天的起始时间（午夜）
	startTime := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	// 获取当天的终止时间（午夜前的最后一秒）
	endTime := startTime.AddDate(0, 0, 1).Add(-time.Second)
	startTimeIn := []any{
		startTime.Format("2006-01-02 15:04:05"),
	}
	endTimeIn := []any{
		endTime.Format("2006-01-02 15:04:05"),
	}
	createdAtMap := make(map[string][]any)
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	filterMap[model.UserTaskLogColumns.UpdatedAt] = createdAtMap
	_, count, err := l.svcCtx.CurrentUser.GetTaskLogList(l.ctx, model.M{}, 0, filterMap)
	if err != nil {
		logrus.Info(fmt.Sprintf("ExecIntegralTaskLog GetTaskLogList err: %+v", err))
		return nil, err
	}
	//0为无限制
	if *in.TaskFrequency != 0 && uint32(count) >= *in.TaskFrequency {
		return nil, resultx.StatusError(resultx.INTEGRAL_TASK_FINISHES_NUMBER_EXCEED, "")
	}
	var gems, growth uint64
	var slug string
	status := uint8(globalkey.StatusEnabled)
	if in.TaskSlug != nil && len(strings.TrimSpace(*in.TaskSlug)) > 0 {
		slug = *in.TaskSlug
	}

	if in.Gems != nil && *in.Gems > 0 {
		gems = *in.Gems
	}

	if in.Growth != nil && *in.Growth > 0 {
		growth = *in.Growth
	}

	if in.Status != nil && *in.Status > 0 {
		status = uint8(*in.Status)
	}
	//任务记录表
	log := &model.UserTaskLog{
		UserID:    *in.UserId,
		TaskID:    *in.TaskId,
		TaskName:  *in.TaskName,
		TaskSlug:  slug,
		Gems:      uint(*in.Integrals),
		Growth:    uint(gems),
		Integrals: uint(growth),
		Status:    status,
		CreatedAt: now,
		UpdatedAt: now,
	}
	err = l.svcCtx.CurrentUser.InsertTaskLog(l.ctx, tx, log)
	if err != nil {
		logrus.Info(fmt.Sprintf("ExecIntegralTaskLog InsertTaskLog err: %+v", err))
		tx.Rollback()
		return nil, err
	}
	//积分交易记录表
	err = l.svcCtx.CurrentUser.InsertTransactionLog(l.ctx, tx, &model.UserTransactionLog{
		UserID: *in.UserId,
		//UserName:             "",
		AssetType:    uint8(globalkey.UserAssetTypePoint),
		ChangeType:   uint8(globalkey.UserAssetChangeTypeIncrease),
		ChangeAmount: strconv.FormatInt(int64(*in.Integrals), 10),
		SourceType:   uint8(globalkey.UserAssetSourceTypeTask),
		SourceID:     log.ID,
		Desc:         *in.TaskName,
		Status:       status,
		CreatedAt:    now,
		UpdatedAt:    now,
	})
	if err != nil {
		logrus.Info(fmt.Sprintf("ExecIntegralTaskLog InsertTransactionLog err: %+v", err))
		tx.Rollback()
		return nil, err
	}
	//用户增加积分
	err = l.svcCtx.CurrentUser.IncreaseIntegralBatch(l.ctx, tx, []uint64{*in.UserId}, int(*in.Integrals))
	if err != nil {
		logrus.Info(fmt.Sprintf("ExecIntegralTaskLog IncreaseBalanceBatch err: %+v", err))
		tx.Rollback()

		return nil, err
	}

	tx.Commit()

	return &user.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
